#  引入MySQLdb包
import MySQLdb

#  输入用户名
def inputUserUserName():
    print("请输入用户名:")
    userName = input()
    return userName

#  输入密码
def inputUserPassword():
    print("请输入密码:")
    password = input()
    return password

#  操作数据库  增删改
def operDB(sql):
    # 打开数据库连接
    db = MySQLdb.connect("150.158.50.120", "root", "Xingyi@888",
                         "mall", charset='utf8')
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()
    # SQL 插入语句
    try:
        # 执行sql语句
        cursor.execute(sql)
        # 提交到数据库执行
        db.commit()  #
    except:
        db.rollback()

#  查数据库
def  queryDb(userName,password):
    #  连接数据库
    db = MySQLdb.connect("150.158.50.120", "root",
                         "Xingyi@888", "mall", charset='utf8')
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()
    # 执行SQL语句
    sql="select  * from  tb_newbee_mall_admin_user t  " \
        "where t.login_user_name= ' "+str(userName)+" ' and t.login_password= ' "\
        +str(password)+" '"

    cursor.execute(sql)
    #  获取数据
    results = cursor.fetchall()
    return results

# 用户登录
def  login():
    # 获取用户名和密码
    userName = inputUserUserName()
    password = inputUserPassword
    results=queryDb(userName,password)
    length=len(results)
    if  length >0 :
        print("用户登录成功")
    else:
        print("用户登录失败")

#   注册用户
def  registerUser():
    print("------注册用户功能------")
    # 获取用户名和密码
    userName=inputUserUserName()
    password=inputUserPassword

    # SQL 插入语句
    sqlInsert = "insert  into tb_newbee_mall_admin_user values " \
          "(5,'"+str(userName)+"','"+str(password)+"'," \
          "'测试账号admin20220429',0) "
    operDB(sqlInsert)

# 修改用户
def  updateUser():
    print("------注册用户功能------")
    # 获取用户名和密码
    userName = inputUserUserName()
    password = inputUserPassword

    #  根据用户名更新密码
    sqlUpdate = " update tb_newbee_mall_admin_user  " \
                "set login_password='" + str(password) + "" \
                    "' where login_password='"+str(userName)+"'"
    operDB(sqlUpdate)

